package com.yfq.springframework.beans.support;

import com.yfq.springframework.beans.BeansException;
import com.yfq.springframework.beans.factory.ConfigurableListableBeanFactory;
import com.yfq.springframework.beans.config.BeanDefinition;
import com.yfq.springframework.support.BeanDefinitionRegistry;

import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author 姚凤桥
 * @date 2023/1/8 17:44
 * @description
 */
public class DefaultListableBeanFactory extends AbstractAutowiredCapableBeanFactory
        implements BeanDefinitionRegistry, ConfigurableListableBeanFactory {
    private final Map<String, BeanDefinition> beanDefinitionMap = new HashMap<>();

    @Override
    public void registerBeanDefinition(String beanName, BeanDefinition beanDefinition) {
        beanDefinitionMap.put(beanName, beanDefinition);
    }

    @Override
    public boolean containsBeanName(String beanName) {
        return beanDefinitionMap.containsKey(beanName);
    }

    @Override
    public BeanDefinition getBeanDefinition(String beanName) {
        return beanDefinitionMap.get(beanName);
    }

    @Override
    public void preInstantiateSingletons() throws BeansException {
        beanDefinitionMap.keySet().forEach(this::getBean);
    }

    @Override
    @SuppressWarnings("unchecked")
    public <T> Map<String, T> getBeansOfType(Class<T> type) throws BeansException {
        return beanDefinitionMap.keySet().stream().filter(beanName -> {
            BeanDefinition beanDefinition = beanDefinitionMap.get(beanName);
            Class<?> clazz = beanDefinition.getBeanClass();

            return type.isAssignableFrom(clazz);
        }).collect(Collectors.toMap(
                beanName -> beanName,
                beanName -> (T) getBean(beanName),
                (o1, o2) -> o2)
        );
    }

    @Override
    public String[] getBeanDefinitionNames() {
        return beanDefinitionMap.keySet().toArray(new String[0]);
    }
}
